//引入store文件
import store from "@/store"
var url = "ws:/192.168.43.236:8089/websocket/";
var ws;
var tt; // 延时器
var lockReconnect = false; //避免重复连接
var retryCount = 3; //断线重连次数
var numberOfRetries = 1; //已重试次数 
var clientId = localStorage.getItem('userId');

/**
 * 初始化webscoket
 */
var websocket = {
	// 初始化
	Init: function(clientId) {
		this.clientId=clientId;
		if(clientId==null||clientId==''){
			return;
		}
		console.log('连接的用户ID--》》', clientId)
		if ("WebSocket" in window) {
			ws = new WebSocket(url + clientId);
			console.log('WebSocket')
		} else if ("MozWebSocket" in window) {
			ws = new MozWebSocket(url + clientId);
			console.log('MozWebSocket')
		} else {
				console.log('您的浏览器不支持 WebSocket!');
			return;
		}

		// 接收消息
		ws.onmessage = function(e) {
			console.log("socket接收到的消息：",e.data);
			
			heartCheck.start()
			if (e.data == 'ok') { //心跳消息不做处理
				return
			}
			//处理消息
			messageHandle(e.data)
		}

		ws.onclose = function() {
		
			console.log('socket连接已关闭');
			reconnect(clientId);
		}

		// 连接成功
		ws.onopen = function() {
			console.log("连接成功")
			// 心跳检测
			heartCheck.start();
		}

		// 错误
		ws.onerror = function(e) {
			console.log("数据传输发生错误");
		
			reconnect(clientId)
		}
	},
	// 发送消息
	Send: function(msgObj) {
		console.log("消息--》",msgObj);
		let msg = JSON.stringify(msgObj);
		console.log("JSON消息--》",msg);
		ws.send(msg);
	},

	getWebSocket() {
		return ws;
	},

	getStatus() {
		if (ws.readyState == 0) {
			return "未连接";
		} else if (ws.readyState == 1) {
			return "已连接";
		} else if (ws.readyState == 2) {
			return "连接正在关闭";
		} else if (ws.readyState == 3) {
			return "连接已关闭";
		}
	}
}

export default websocket;

/**
 * 处理消息
 * @param {Object} message 消息
 */
function messageHandle(message) {
	//获取当前页面路由，判断所处位置
	// let href=window.location.href;
	// let router=href.substring(href.indexOf("#")+1);
	// console.log("当前页面路由--》",router);
	
	//调用store.js中的actions下的oddJIa方法
	store.dispatch("device/setMessage",message);

}

/**
 * 断线重连
 * @param {*} sname 用户ID 
 */
function reconnect(sname) {

	if (lockReconnect) {
		return;
	};
	lockReconnect = true;

	//没连接上会一直重连，设置延迟避免请求过多
	tt && clearTimeout(tt);
	// setTimeout
	tt = setInterval(function() {
		console.log("执行断线重连...", numberOfRetries)
		if (retryCount === numberOfRetries) {
			lockReconnect = true;
			return;
		}

		numberOfRetries++;
		websocket.Init(sname);
		lockReconnect = false;
	}, 4000);
}

/**
 * 心跳检测
 */
var heartCheck = {
	timeout: 1000 * 60 * 3, // 心跳检测间隔 3分钟
	timeoutObj: null,
	serverTimeoutObj: null,
	start: function() {
		console.log('开始心跳检测');
		var self = this;
		this.timeoutObj && clearTimeout(this.timeoutObj);
		this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
		this.timeoutObj = setInterval(function() { // 定时向服务器发送心跳信号
			//这里发送一个心跳，后端收到后，返回一个心跳消息，
			//onmessage拿到返回的心跳就说明连接正常
			console.log('心跳检测...');
			ws.send("HeartBeat:" + clientId);
			self.serverTimeoutObj = setInterval(function() { // 定时检测 ws是否连接正常
				if (ws.readyState != 1) { //ws状态为1表示连接成功
					ws.close();
				}
				// createWebSocket();
			}, self.timeout);

		}, this.timeout)
	}
}
